package com.util;

import com.rabbitmq.client.*;

import java.util.Map;

public class RabbitmqUtils {
    private static ConnectionFactory factory = new ConnectionFactory();
    private static String message;

    static {
        factory.setHost("192.168.159.142");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
    }

    private static Channel getChannel() throws Exception {
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        return channel;
    }

    public static void send(String queue, boolean duration, boolean exclusive,
                            boolean autoDelete, Map<String, Object> args,
                            String message) {
        Channel channel = null;
        try {
            channel = getChannel();
            channel.queueDeclare(queue, duration, exclusive, autoDelete, args);
            channel.basicPublish("", queue, null, message.getBytes());
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            RabbitmqUtils.close(channel);
        }
    }

    public static void receive(String queue, boolean duration, boolean exclusive,
                               boolean autoDelete, Map<String, Object> args,
                               DeliverCallback deliverCallback) {
        Channel channel = null;
        try {
            channel = getChannel();
            channel.queueDeclare(queue, duration, exclusive, autoDelete, args);
            channel.basicConsume(queue, true, deliverCallback, consumerTag -> {});
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            RabbitmqUtils.close(channel);
        }
    }

    public static void receiveByWQ(String queue, boolean duration, boolean exclusive,
                                   boolean autoDelete, Map<String, Object> args,
                                   DeliverCallback deliverCallback, CancelCallback cancelCallback) {
        Channel channel = null;
        try {
            channel = getChannel();
            channel.queueDeclare(queue, duration, exclusive, autoDelete, args);
            channel.basicConsume(queue, true, deliverCallback, cancelCallback);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            RabbitmqUtils.close(channel);
        }
    }

    private static void close(Channel channel) {
        try {
            if (channel != null) {
                Connection connection = channel.getConnection();
                channel.close();
                connection.close();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
